package com.bcxj.apiboss.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bcxj.apiboss.mapper.AdminUserMapper;
import com.bcxj.internalcommon.constant.CommonStatusEnum;
import com.bcxj.internalcommon.constant.IdentityConstant;
import com.bcxj.internalcommon.constant.TokenConstant;
import com.bcxj.internalcommon.entity.AdminUser;
import com.bcxj.internalcommon.response.ResponseResult;
import com.bcxj.internalcommon.util.AESUtil;
import com.bcxj.internalcommon.util.ImagesUtil;
import com.bcxj.internalcommon.util.JwtUtils;
import com.bcxj.internalcommon.util.RedisPrefixUtils;
import com.bcxj.internalcommon.vo.AdminUserVO;
import com.bcxj.internalcommon.vo.TokenVO;
import com.xiaoleilu.hutool.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: AdminUserService
 * Package: com.bcxj.apiboss.service
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/4/26 11:57
 * @Version 1.0
 * @Since 1.0
 */
@Service
public class AdminUserService {

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 管理员登录
     *
     * @param account
     * @param password
     * @return
     */
    public ResponseResult adminLogin(String account, String password) throws Exception {
        // 1 校验账号是否存在
        // 1.1 查询数据库数据
        AdminUser adminUser = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUser>()
                .eq(AdminUser::getAccount, account)
                .eq(AdminUser::getPassword, AESUtil.encrypt(password)));

        if(null == adminUser) {
            return ResponseResult.fail(CommonStatusEnum.ADMIN_ERROR);
        }

        // 校验成功, 颁发toke
        String accessToken = JwtUtils.generatorToken(adminUser.getPhone(), IdentityConstant.ADMIN_IDENTITY, TokenConstant.ACCESS_TOKEN);
        String refreshToken = JwtUtils.generatorToken(adminUser.getPhone(), IdentityConstant.ADMIN_IDENTITY, TokenConstant.REFRESH_TOKEN);
        // 3. token存入Redis中的数据
        String accessTokenKey = RedisPrefixUtils.generatorTokenKey(adminUser.getPhone(), IdentityConstant.ADMIN_IDENTITY, TokenConstant.ACCESS_TOKEN);
        String refreshTokenKey = RedisPrefixUtils.generatorTokenKey(adminUser.getPhone(), IdentityConstant.ADMIN_IDENTITY, TokenConstant.REFRESH_TOKEN);
        // 3.1. 将token存入redis
        redisTemplate.opsForValue().set(accessTokenKey, accessToken, 30, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 1, TimeUnit.DAYS);

        // 3.2 返回token
        TokenVO tokenResponse = new TokenVO();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);
        return ResponseResult.success(tokenResponse);
    }

    public ResponseResult getAdmin(String phone) {
        AdminUser adminUser = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUser>().eq(AdminUser::getPhone, phone));

        if(null == adminUser) {
            return ResponseResult.fail("系统无该用户");
        }
        return ResponseResult.success(adminUser);
    }


    /**
     * 增加用户
     * @param adminUser
     * @return
     */
    public ResponseResult addAdmin(AdminUser adminUser) throws Exception {
        adminUser.setImages(ImagesUtil.getRanImage());
        adminUser.setPassword(AESUtil.encrypt(adminUser.getPassword()));
        adminUserMapper.insert(adminUser);
        return ResponseResult.success();
    }


    /**
     * 获取全部用户的信息
     * @return
     */
    public ResponseResult getAll() {
        List<AdminUser> adminUsers = adminUserMapper.selectList(null);
        ArrayList<AdminUserVO> adminUserVOS = new ArrayList<>();
        for (int i = 0; i < adminUsers.size(); i++) {
            AdminUserVO userVO = new AdminUserVO();
            BeanUtil.copyProperties(adminUsers.get(i), userVO);
            adminUserVOS.add(userVO);
        }
        return ResponseResult.success(adminUserVOS);
    }


    /**
     * 更新管理员信息
     * @param adminUserVO
     * @return
     */
    public ResponseResult updateAdmin(AdminUserVO adminUserVO) {
        // 1 拷贝对应的属性
        AdminUser adminUser = new AdminUser();
        BeanUtil.copyProperties(adminUserVO, adminUser);


        // 2 更新用户的信息
        // 2.1 判断id以及一些必要属性
        if(null == adminUser.getId()) {
            return ResponseResult.fail("管理员信息更新错误");
        }
        // 2.2 更新用户的信息
        adminUserMapper.updateById(adminUser);

        // 3 返回成功信息
        return ResponseResult.success();
    }
}
